<template>

  <div class="app-container" v-if="canList">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" class="filter-item input" placeholder="转账人编号"
                style="width: 200px;"
                v-model="listQuery.entity.fromUser.code">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" class="filter-item input" placeholder="到账人编号"
                style="width: 200px;"
                v-model="listQuery.entity.toUser.code">
      </el-input>

      <el-input @keyup.enter.native="handleFilter" class="filter-item input" placeholder="相关订单编号"
                style="width: 200px;"
                v-model="listQuery.entity.record.orderNo">
      </el-input>
      <el-select @change='handleFilter' class="filter-item input" clearable placeholder="类型"
                 style="width: 130px"
                 v-model="listQuery.entity.record.type">
        <el-option :key="item" :label="item" :value="index" v-for="(item,index) in  typeOptions">
        </el-option>
      </el-select>

      <el-select @change='handleFilter' class="filter-item input" clearable placeholder="业务"
                 style="width: 130px"
                 v-model="listQuery.entity.record.bus">
        <el-option :key="item" :label="item" :value="index" v-for="(item,index) in  busOptions">
        </el-option>
      </el-select>
      <el-date-picker
          @change='handleFilter'
          class="filter-item input"
          end-placeholder="变动时间结束日期"
          range-separator="至"
          start-placeholder="变动时间开始日期"
          type="datetimerange"
          v-model="listQuery.entity.record.times"
          value-format="yyyy-MM-dd HH:mm:ss">
      </el-date-picker>

      <div style="display: inline-block">

        <el-button @click="handleFilter" class="filter-item" icon="el-icon-search" style="margin-left: 10px;" type="primary"
                   v-waves>查找
        </el-button>

        <el-button :loading="downloadLoading" @click="handleDownload" class="filter-item" icon="el-icon-download" type="primary"
                   v-waves>导出
        </el-button>
      </div>
    </div>

    <el-table :data="list" :key='tableKey' border  highlight-current-row
              v-loading="listLoading">
      <yf-table-column align="center" label="ID">
        <template slot-scope="scope">
          <span>{{scope.row.record.id}}</span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="转账人">
        <template slot-scope="scope">
          <span v-if="scope.row.fromUser">{{scope.row.fromUser.code}}-{{scope.row.fromUser.name}}</span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="到账人">
        <template slot-scope="scope">
          <span v-if="scope.row.toUser">{{scope.row.toUser.code}}-{{scope.row.toUser.name}}</span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="变动数量">
        <template slot-scope="scope">
          <span v-if="scope.row.record">{{scope.row.record.amount}}</span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="类型">
        <template slot-scope="scope">
                                                <span v-if="scope.row.record">

                         <el-tag :type="tagTypes[scope.row.record.type]">     {{typeOptions[scope.row.record.type]}}</el-tag>

                        </span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="状态">
        <template slot-scope="scope">
                                                <span v-if="scope.row.record">

                         <el-tag :type="tagTypes[scope.row.record.status]">     {{statusOptions[scope.row.record.status]}}</el-tag>

                        </span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="业务">
        <template slot-scope="scope">
                                                <span v-if="scope.row.record">

                         <el-tag :type="tagTypes[scope.row.record.bus]">     {{busOptions[scope.row.record.bus]}}</el-tag>

                        </span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="转账人剩余">
        <template slot-scope="scope">
          <span v-if="scope.row.record">{{scope.row.record.fromNowAmount}}</span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="到账人数量">
        <template slot-scope="scope">
          <span v-if="scope.row.record">{{scope.row.record.toNowAmount}}</span>
        </template>
      </yf-table-column>

      <!--            <yf-table-column align="center" label="">-->
      <!--                <template slot-scope="scope">-->
      <!--                    <span v-if="scope.row.record">{{scope.row.record.hide}}</span>-->
      <!--                </template>-->
      <!--            </yf-table-column>-->


      <yf-table-column align="center" label="变动时间" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.record">{{parseTime(scope.row.record.time)}}</span>
        </template>
      </yf-table-column>

      <yf-table-column align="center" label="备注">
        <template slot-scope="scope">
          <span v-if="scope.row.record">{{scope.row.record.info}}</span>
        </template>
      </yf-table-column>
      <yf-table-column align="center" label="相关订单编号">
        <template slot-scope="scope">
          <span v-if="scope.row.record">{{scope.row.record.orderNo}}</span>
        </template>
      </yf-table-column>

      <!--            <yf-table-column align="center" class-name="small-padding fixed-width" label="操作" width="230">-->
      <!--                <template slot-scope="scope">-->
      <!--                    <el-button @click="handleUpdate(scope)" size="mini" type="primary" v-if="canUpdate">编辑</el-button>-->
      <!--                    <el-button @click="handleDelete(scope)" size="mini" type="danger"-->
      <!--                               v-if="canSave">删除-->
      <!--                    </el-button>-->
      <!--                </template>-->
      <!--            </yf-table-column>-->

    </el-table>

    <div class="pagination-container" style="margin-top: 20px">
      <el-pagination :current-page="listQuery.page" :page-size="listQuery.limit" :page-sizes="[10,20,30, 50]"
                     :total="total" @current-change="handleCurrentChange" @size-change="handleSizeChange"
                     background layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="temp" :rules="rules" label-position="left" label-width="120px" ref="dataForm"
               style='width: 450px; margin-left:50px;'>
        <el-form-item label="转账人" prop="fromUserId">
          <el-input v-model="temp.record.fromUserId"></el-input>
        </el-form-item>
        <el-form-item label="到账人" prop="toUserId">
          <el-input v-model="temp.record.toUserId"></el-input>
        </el-form-item>
        <el-form-item label="变动数量" prop="amount">
          <el-input v-model="temp.record.amount"></el-input>
        </el-form-item>
        <el-form-item label="转账人剩余数量" prop="fromNowAmount">
          <el-input v-model="temp.record.fromNowAmount"></el-input>
        </el-form-item>
        <el-form-item label="到账人剩余数量" prop="toNowAmount">
          <el-input v-model="temp.record.toNowAmount"></el-input>
        </el-form-item>
        <el-form-item label="变动原因" prop="info">
          <el-input v-model="temp.record.info"></el-input>
        </el-form-item>
        <el-form-item label="" prop="hide">
          <el-input v-model="temp.record.hide"></el-input>
        </el-form-item>
        <el-form-item label="相关订单编号" prop="orderNo">
          <el-input v-model="temp.record.orderNo"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="status">
          <el-select class="filter-item" placeholder="类型" v-model="temp.record.type">
            <el-option :key="item" :label="item" :value="index"
                       v-for="(item,index) in  typeOptions">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select class="filter-item" placeholder="状态" v-model="temp.record.status">
            <el-option :key="item" :label="item" :value="index"
                       v-for="(item,index) in  statusOptions">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务" prop="status">
          <el-select class="filter-item" placeholder="业务" v-model="temp.record.bus">
            <el-option :key="item" :label="item" :value="index"
                       v-for="(item,index) in  busOptions">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="变动时间" prop="date">
          <el-date-picker placeholder="变动时间" type="datetime"
                          v-model="temp.record.time" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeDialogForm">取消</el-button>
        <el-button @click="createData" type="primary" v-if="dialogStatus=='create'">确认</el-button>
        <el-button @click="updateData" type="primary" v-else>确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style type="stylus">
.filter-container {
  /*padding-bottom: 20px;*/
}

.filter-item {
  margin-bottom: 10px;
}

.filter-item.input {
  /*line-height: 60px*/
  margin-right: 10px;
}
</style>

<script>
import {down,options, info, list, remove, save, update} from '@/api/account_record'
import waves from '@/directive/waves' // 水波纹指令
import {parseTime} from '@/utils'
import {downExcel} from '@/utils/down.js'

import {mapGetters} from 'vuex'
import {hasAuth} from '@/utils/auth'

export default {
  name: 'test',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      time: null
      ,
      listQuery: {
        page: 1,
        limit: 20,
        order: 'record.id desc',
        entity: {
          record:
              {
                id: null,
                fromUserId: null,
                toUserId: null,
                type: null,
                status: null,
                bus: null,
                amount: null,
                fromNowAmount: null,
                toNowAmount: null,
                time: null,
                info: null,
                orderNo: null
              }
          , fromUser:
              {
                id: null,
                name: null,
                avatar: null,
                phone: null,
                birth: null,
                pid: null,
                levelId: null,
                time: null,
                openId: null,
                unionId: null,
                code: null
              }
          , toUser:
              {
                id: null,
                name: null,
                avatar: null,
                phone: null,
                birth: null,
                pid: null,
                levelId: null,
                time: null,
                openId: null,
                unionId: null,
                code: null
              }
        }
      },
      typeOptions: [],
      statusOptions: [],
      busOptions: [],
      tagTypes: ['info', '', 'warning', 'danger', 'warning'],
      temp: {

        record:
            {
              id: null,
              fromUserId: null,
              toUserId: null,
              type: null,
              status: null,
              bus: null,
              amount: null,
              fromNowAmount: null,
              toNowAmount: null,
              time: null,
              info: null,
              hide: null,
              orderNo: null
            }
        , fromUser:
            {
              id: null,
              name: null,
              avatar: null,
              phone: null,
              birth: null,
              pid: null,
              levelId: null,
              time: null,
              openId: null,
              unionId: null,
              code: null
            }
        , toUser:
            {
              id: null,
              name: null,
              avatar: null,
              phone: null,
              birth: null,
              pid: null,
              levelId: null,
              time: null,
              openId: null,
              unionId: null,
              code: null
            }


      }
      ,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      }
      ,
      rules:
          {
            fromUserId: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            toUserId: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            type: [
              {
                required: false,
                message: '必填字段',
                trigger: 'blur'
              }
            ]
            ,
            status: [
              {
                required: false,
                message: '必填字段',
                trigger: 'blur'
              }
            ]
            ,
            bus: [
              {
                required: false,
                message: '必填字段',
                trigger: 'blur'
              }
            ]
            ,
            amount: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            fromNowAmount: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            toNowAmount: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            time: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            info: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            hide: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
            ,
            orderNo: [
              {
                required: false,
                message: '必填字段',
                trigger: 'change'
              }
            ]
          }
      ,
      downloadLoading: false,
      qData:
          {
            token: '',
            key: ''
          }
    }
  },
  activated() {
    this.getList()
    this.getOptions()
  },
  computed: {
    ...mapGetters([
      'perms'
    ]),
    canSave() {
      return hasAuth(this.perms, 'account:record:save')
    },
    canDelete() {
      return hasAuth(this.perms, 'account:record:delete')
    },
    canUpdate() {
      return hasAuth(this.perms, 'account:record:update')
    },
    canList() {
      return hasAuth(this.perms, 'account:record:list')
    }
  },
  methods: {
    parseTime(time) {
      if (!time) return ''
      return parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}')
    },
    getList() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getOptions(){
      options().then(res => {
        this.typeOptions =res.data.typeOptions
        this.statusOptions =res.data.statusOptions
        this.busOptions =res.data.busOptions
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    beforeFormShow(row) {
      this.resetTemp(row) // 更新数据
      // 存在图片

    },
    afterFormShow(row) {

    },
    beforeFormCommit() {
    },
    resetTemp(row) {

      this.temp = {
        record: {}
        , fromUser: {}
        , toUser: {}
      }
      if (row) {
        this.temp = Object.assign({}, row) // copy obj
      }

    },
    handleCreate() {
      this.beforeFormShow()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.afterFormShow()
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(scope) {
      this.index = scope.$index
      // this.beforeFormShow(scope.row)
      // this.temp = Object.assign({}, row) // copy obj
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
        this.deleteData()
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '删除失败'
        })
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.beforeFormCommit()

              save(this.temp).then(res => {
                this.temp = res.data
                this.list.unshift(this.temp)
                this.closeDialogForm()
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              })
            }
          }
      )
    },
    deleteData() {
      // const ids = [this.temp.record.id]
      const ids = [this.list[this.index].record.id]
      remove({ids: ids}).then(res => {
        // 从当前队列中移除
        this.list.splice(this.index, 1)
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleUpdate(scope) {
      info(scope.row.record.id).then(res => {
        this.temp = res.data
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.beforeFormCommit()
              update(this.temp).then(() => {
                this.list.splice(this.index, 1, this.temp)
                this.closeDialogForm()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              })
            }
          }
      )
    },
    closeDialogForm() {
      this.dialogFormVisible = false
    },
    handleDownload() {
      this.downloadLoading = true
      down(this.listQuery).then(res => {
        downExcel(res)
        this.downloadLoading = false
        this.$notify({
          title: '成功',
          message: '下载成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    // formatJson(filterVal, jsonData) {
    //     return jsonData.map(v => filterVal.map(j => {
    //         return v[j]
    //     }
    // ))
    // },
  }
}
</script>
